package com.ruoyi.merchant.service.impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.merchant.domain.Merchant;
import com.ruoyi.merchant.domain.MerchantBankCard;
import com.ruoyi.merchant.domain.dto.AddBankCardDTO;
import com.ruoyi.merchant.domain.vo.BankCardDetailVO;
import com.ruoyi.merchant.domain.vo.BankCardVO;
import com.ruoyi.merchant.enums.BankCardStatusEnum;
import com.ruoyi.merchant.enums.CardTypeEnum;
import com.ruoyi.merchant.mapper.MerchantBankCardMapper;
import com.ruoyi.merchant.mapper.MerchantMapper;
import com.ruoyi.merchant.service.IMerchantBankCardService;
import com.ruoyi.merchant.utils.MerchantSecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 商家银行卡Service业务层处理
 */
@Service
public class MerchantBankCardServiceImpl implements IMerchantBankCardService {
    
    @Autowired
    private MerchantBankCardMapper bankCardMapper;

    @Autowired
    private MerchantMapper merchantMapper;
    
    /**
     * 添加银行卡
     *
     * @param addDTO 银行卡信息
     * @return 银行卡ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addBankCard(AddBankCardDTO addDTO) {
        // 获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        if (merchantId == null) {
            throw new ServiceException("未登录或登录已过期");
        }

        // 2. 查询商家信息，获取关联的若依 user_id
        Merchant merchant = merchantMapper.selectMerchantById(merchantId);
        if (merchant == null) {
            throw new ServiceException("商家信息不存在");
        }
        Long userId = merchant.getUserId();

        // 检查银行卡是否已存在（全局唯一）
        // 这里的逻辑是：只要这张卡在系统里（且没被软删除），任何人都不能再绑
        int count = bankCardMapper.checkBankCardExists(addDTO.getCardNumber());
        if (count > 0) {
            // 这里提示语也可以改得更明确一点，或者模糊一点以保护隐私
            throw new ServiceException("该银行卡已被绑定，请更换其他银行卡");
        }
        
        // 如果设置为默认卡，先取消其他默认卡
        if (Boolean.TRUE.equals(addDTO.getSetAsDefault())) {
            bankCardMapper.cancelDefaultBankCard(merchantId);
        }
        
        // 构建银行卡实体
        MerchantBankCard bankCard = new MerchantBankCard();
        BeanUtils.copyProperties(addDTO, bankCard);
        bankCard.setMerchantId(merchantId);
        bankCard.setUserId(userId);
        bankCard.setIsDefault(Boolean.TRUE.equals(addDTO.getSetAsDefault()) ? 1 : 0);
        bankCard.setIsVerified(0); // 默认未验证
        bankCard.setStatus(1); // 默认启用
        
        // 自动推断银行编码（如果前端没传）
        if (StringUtils.isEmpty(bankCard.getBankCode())) {
            bankCard.setBankCode(generateBankCode(addDTO.getBankName()));
        }
        
        // 插入数据库
        int rows = bankCardMapper.insertBankCard(bankCard);
        if (rows == 0) {
            throw new ServiceException("添加银行卡失败");
        }
        
        // TODO: 模拟场景直接通过验证，真实场景需要调用四要素验证接口
        // simulateVerifyBankCard(bankCard.getCardId());
        
        return bankCard.getCardId();
    }
    
    /**
     * 查询银行卡列表
     *
     * @return 银行卡列表
     */
    @Override
    public List<BankCardVO> getBankCardList() {
        // 获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        if (merchantId == null) {
            throw new ServiceException("未登录或登录已过期");
        }
        
        return bankCardMapper.selectBankCardList(merchantId);
    }
    
    /**
     * 查询银行卡详情
     *
     * @param cardId 银行卡ID
     * @return 银行卡详情
     */
    @Override
    public BankCardDetailVO getBankCardDetail(Long cardId) {
        // 获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        if (merchantId == null) {
            throw new ServiceException("未登录或登录已过期");
        }
        
        // 查询银行卡
        MerchantBankCard bankCard = bankCardMapper.selectBankCardById(cardId, merchantId);
        if (bankCard == null) {
            throw new ServiceException("银行卡不存在");
        }
        
        // 转换为VO
        BankCardDetailVO vo = new BankCardDetailVO();
        BeanUtils.copyProperties(bankCard, vo);
        
        // 脱敏处理
        vo.setCardNumber(bankCard.getCardNumber()); // 完整卡号（根据安全要求决定是否返回）
        vo.setCardNumberMasked(maskCardNumber(bankCard.getCardNumber()));
        vo.setCardHolderIdcardMasked(maskIdCard(bankCard.getCardHolderIdcard()));
        vo.setCardHolderPhoneMasked(maskPhone(bankCard.getCardHolderPhone()));
        
        // 设置枚举描述
        vo.setCardTypeName(CardTypeEnum.getDescByCode(bankCard.getCardType()));
        vo.setStatusName(BankCardStatusEnum.getDescByCode(bankCard.getStatus()));
        
        return vo;
    }
    
    /**
     * 设置默认银行卡
     *
     * @param cardId 银行卡ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int setDefaultBankCard(Long cardId) {
        // 获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        if (merchantId == null) {
            throw new ServiceException("未登录或登录已过期");
        }
        
        // 检查银行卡是否存在
        MerchantBankCard bankCard = bankCardMapper.selectBankCardById(cardId, merchantId);
        if (bankCard == null) {
            throw new ServiceException("银行卡不存在");
        }
        
        // 检查银行卡状态
        if (bankCard.getStatus() != 1) {
            throw new ServiceException("银行卡状态异常，无法设为默认");
        }
        
        // 先取消其他默认卡
        bankCardMapper.cancelDefaultBankCard(merchantId);
        
        // 设置当前卡为默认
        return bankCardMapper.setDefaultBankCard(cardId, merchantId);
    }

    /**
     * 删除银行卡
     *
     * @param cardId 银行卡ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBankCard(Long cardId) {
        // 获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        if (merchantId == null) {
            throw new ServiceException("未登录或登录已过期");
        }

        // 检查银行卡是否存在
        MerchantBankCard bankCard = bankCardMapper.selectBankCardById(cardId, merchantId);
        if (bankCard == null) {
            throw new ServiceException("银行卡不存在");
        }

        // 逻辑优化：处理默认卡的删除逻辑
        if (bankCard.getIsDefault() == 1) {
            // 查询该商家名下所有的有效银行卡数量
            // 这一步需要在 Mapper 中加一个 countBankCards 方法
            int count = bankCardMapper.countBankCards(merchantId);

            // 如果名下不止这一张卡，且试图删除默认卡 -> 拦截
            if (count > 1) {
                throw new ServiceException("当前卡为默认提现卡，请先将其他银行卡设为默认后再删除");
            }

            // 如果 count == 1，说明这是唯一的一张卡，虽然是默认卡，但允许删除
            // 删除后，商家就没有默认卡了，下次添加卡时会自动设为默认
        }

        // 软删除
        return bankCardMapper.deleteBankCard(cardId, merchantId);
    }


    /**
     * 验证银行卡
     *
     * @param cardId 银行卡ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int verifyBankCard(Long cardId) {
        // 获取商家ID
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        if (merchantId == null) {
            throw new ServiceException("未登录或登录已过期");
        }
        
        // 检查银行卡是否存在
        MerchantBankCard bankCard = bankCardMapper.selectBankCardById(cardId, merchantId);
        if (bankCard == null) {
            throw new ServiceException("银行卡不存在");
        }
        
        // 如果已验证，直接返回
        if (bankCard.getIsVerified() == 1) {
            return 1;
        }
        
        // TODO: 真实场景：调用第三方四要素验证接口
        // 验证：姓名、身份证号、银行卡号、手机号
        // boolean verifyResult = thirdPartyService.verifyBankCard(
        //     bankCard.getCardHolderName(),
        //     bankCard.getCardHolderIdcard(),
        //     bankCard.getCardNumber(),
        //     bankCard.getCardHolderPhone()
        // );
        // if (!verifyResult) {
        //     throw new ServiceException("银行卡验证失败，请检查信息是否正确");
        // }
        
        // 模拟验证成功
        return bankCardMapper.updateBankCardVerified(cardId, merchantId);
    }
    
    /**
     * 生成银行编码（简单映射）
     *
     * @param bankName 银行名称
     * @return 银行编码
     */
    private String generateBankCode(String bankName) {
        if (bankName.contains("工商")) return "ICBC";
        if (bankName.contains("建设")) return "CCB";
        if (bankName.contains("农业")) return "ABC";
        if (bankName.contains("中国银行")) return "BOC";
        if (bankName.contains("交通")) return "COMM";
        if (bankName.contains("招商")) return "CMB";
        if (bankName.contains("浦发")) return "SPDB";
        if (bankName.contains("民生")) return "CMBC";
        if (bankName.contains("兴业")) return "CIB";
        if (bankName.contains("平安")) return "PAB";
        if (bankName.contains("光大")) return "CEB";
        if (bankName.contains("中信")) return "CITIC";
        return "OTHER";
    }
    
    /**
     * 银行卡号脱敏
     *
     * @param cardNumber 银行卡号
     * @return 脱敏后的卡号
     */
    private String maskCardNumber(String cardNumber) {
        if (StringUtils.isEmpty(cardNumber) || cardNumber.length() < 8) {
            return cardNumber;
        }
        return cardNumber.substring(0, 4) + " **** **** " + cardNumber.substring(cardNumber.length() - 4);
    }
    
    /**
     * 身份证号脱敏
     *
     * @param idCard 身份证号
     * @return 脱敏后的身份证号
     */
    private String maskIdCard(String idCard) {
        if (StringUtils.isEmpty(idCard) || idCard.length() < 8) {
            return idCard;
        }
        return idCard.substring(0, 6) + "********" + idCard.substring(idCard.length() - 4);
    }
    
    /**
     * 手机号脱敏
     *
     * @param phone 手机号
     * @return 脱敏后的手机号
     */
    private String maskPhone(String phone) {
        if (StringUtils.isEmpty(phone) || phone.length() != 11) {
            return phone;
        }
        return phone.substring(0, 3) + "****" + phone.substring(7);
    }
}
